Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix error occurring in useEffect on hmr #308

Open
wants to merge 28 commits into
base: main
Choose a base branch
from

Conversation

PatrykWalach
Copy link
Collaborator

Rebase of #264

@PatrykWalach PatrykWalach force-pushed the fix-use-effect-error-on-hmr-rebase-2 branch from 9b897fd to e9d1845 Compare January 6, 2025 23:03
Copy link
Collaborator

@rbalicki2 rbalicki2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm, just rewrote the comment slightly for grammar and clarity

Copy link
Collaborator

@rbalicki2 rbalicki2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I forgot to do a thorough review before accepting 😂 Do we also need this in useUpdatableDisposableState?

If so, there are probably enough places where we do this that it makes sense to have a useEffectIgnoringHmrAndStrictMode hook.

It might return the lastCommittedParentCache, in which case we don't need to do anything extra in useCachedResponsivePreCommitValue

@@ -51,6 +51,14 @@ export function useCachedResponsivePrecommitValue<T>(
const lastCommittedParentCache = useRef<ParentCache<T> | null>(null);

useEffect(() => {
// react reruns all `useEffect` in HMR since it doesn't know if the
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    // Since React doesn't know if the code inside of a useEffect has changed,
    // it unmounts and remounts all useEffect calls when doing HMR. This breaks
    // this hook's assumptions! The `onCommit` is called twice.
    //
    // Since this is a library, the user can't change this code, so we are safe
    // to skip this rerun.
    //
    // This also prevents the useEffect from running twice in Strict Mode.

useEffect(() => {
// react reruns all `useEffect` in HMR since it doesn't know if the
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    // Since React doesn't know if the code inside of a useEffect has changed,
    // it unmounts and remounts all useEffect calls when doing HMR. This breaks
    // this hook's assumptions! The cleanupFn is called unexpectedly during HMR,
    // and the item is not recreated. (Even recreating the item would be a bad outcome,
    // as that would reissue network requests.)
    //
    // Since this is a library, the user can't change this code, so we are safe
    // to skip this rerun.
    //
    // This also prevents the useEffect from running twice in Strict Mode.


useEffect(
function cleanupItemCleanupPairRefIfSetStateNotCalled() {
if (lastCommittedParentCache.current === parentCache) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    // Since React doesn't know if the code inside of a useEffect has changed,
    // it unmounts and remounts all useEffect calls when doing HMR. This breaks
    // this hook's assumptions! The item in the `itemCleanupPairRef` will be disposed.
    //
    // Since this is a library, the user can't change this code, so we are safe
    // to skip this rerun.
    //
    // This also prevents the useEffect from running twice in Strict Mode.

Do we also need to have this check above, in the other useEffect?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second one will not throw because it sets the ref to null. However, because of this, we will lose the current state, which is not perfect.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, seems better to not set it to null!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wait, this should be good, because it will cleanup only when we set with a function and when the ref is still not cleaned up, hmr shouldn't be able to trigger it twice

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wdym? Which useEffect are you referring to?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffect(
    function cleanupItemCleanupPairRefAfterSetState() {
      if (stateFromDisposableStateHook !== UNASSIGNED_STATE) {
        if (itemCleanupPairRef.current !== null) {
          itemCleanupPairRef.current[1]();
          itemCleanupPairRef.current = null;
        } else {
          throw new Error(
            'itemCleanupPairRef.current is unexpectedly null. ' +
              'This indicates a bug in react-disposable-state.',
          );
        }
      }
    },
    [stateFromDisposableStateHook],
  );

This one should cleanup only when these two conditions are met, reruning this on hmr has no effect.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I posted this stuff way too quickly. This will throw on hmr but I think just removing the throw should be enough

@PatrykWalach
Copy link
Collaborator Author

PatrykWalach commented Jan 11, 2025

The solution used here is not good

  • on the first render useEffect will execute (commit and return cleanup)
  • on hmr it will cleanup, then the guard will prevent another execute (commit and return cleanup)

so we end up in a cleaned-up state

The reason it doesn't cause any issues now is probably because of gcBuffer.

@rbalicki2
Copy link
Collaborator

Ah yeah, you're totally right. Good call re: gcBuffer. I'm going to think about this. I wonder if we need to try to detect HMR/double mounting more directly.

@PatrykWalach
Copy link
Collaborator Author

PatrykWalach commented Jan 13, 2025

on useEffect cleanup we will set itemCleanupPairRef to null, if the component unmounted this has no effect, if it was hmr then cache will once again go through temporaryRetain cycle.

This is not tested. It might be easier to test after merging the second pull request.

@PatrykWalach PatrykWalach force-pushed the fix-use-effect-error-on-hmr-rebase-2 branch from d3de5d4 to 50f95ea Compare January 13, 2025 20:20
…fect-error-on-hmr-rebase-2' of github.com:PatrykWalach/isograph into fix-use-effect-error-on-hmr-rebase-2
@PatrykWalach
Copy link
Collaborator Author

PatrykWalach commented Jan 13, 2025

Now the cycle is

  • commit -> cache is populated
  • cleanup -> set maybeHiddenOrFastRefresh to true, clean up cache
    if component is unmounted, that's the end, if it's hmr:
  • commit -> read maybeHiddenOrFastRefresh and skip cacheItem.permanentRetainIfNotDisposed so there's no error, repopulate cache

so at the end we are in the populated state.

we don't need to set itemCleanupPairRef to null because cleanup runs just before cache is populated which will override itemCleanupPairRef and there are no renders in between.

useUpdatableDisposableState still needs to be fixed and it can't be fixed in the same way, as there's no way to repopulate 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants